/*
@file: io.cpp
@author: ZZH
@date: 2022-10-14
@info: io读取数据函数
*/
#include "libFun.h"
#include <QFile>

EXPORT void read_file(pFunCallArg_t pArgs, BasicType* output)
{
    int allCalNum = pArgs->allCalNum;
    char* arg0 = (char*) *(size_t*) pArgs->args[0];//文件名
    size_t arg1 = *static_cast<BasicType*>(pArgs->args[1]);//偏移量(以行为单位)

    for (int i = 0; i < allCalNum; i++)
        output[i] = 0;

    QFile file(arg0);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        const auto& lineList = file.readAll().split('\n');
        auto pt = lineList.begin();
        auto end = lineList.end();

        file.close();

        // for (size_t i = 0;i < arg1;i++)
        //     pt++;

        pt += arg1;

        for (int i = 0;i < allCalNum && pt != end;i++, pt++)
        {
            const QString& line = pt->trimmed();//file.readLine(64).trimmed();

            if (line.isEmpty())
                break;

            if (line.startsWith("0x"))
                output[i] = line.toInt(nullptr, 16);
            else if (line.startsWith("0b"))
                output[i] = line.right(line.length() - 2).toInt(nullptr, 2);
            else
                output[i] = line.toFloat();
        }
    }

    file.close();
}

EXPORT void write_file(pFunCallArg_t pArgs, BasicType* output)
{
    int allCalNum = pArgs->allCalNum;
    char* arg0 = (char*) *(size_t*) pArgs->args[0];//文件名
    BasicType* arg1 = static_cast<BasicType*>(pArgs->args[1]);//要写入的数据

    memcpy(output, arg1, sizeof(BasicType) * allCalNum);

    QFile file(arg0);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
    {
        for (int i = 0;i < allCalNum;i++)
        {
            file.write(QString::number(arg1[i]).toStdString().c_str());
            file.write("\n");
        }
    }

    file.close();
}

EXPORT void append_file(pFunCallArg_t pArgs, BasicType* output)
{
    int allCalNum = pArgs->allCalNum;
    char* arg0 = (char*) *(size_t*) pArgs->args[0];
    BasicType* arg1 = static_cast<BasicType*>(pArgs->args[1]);

    memcpy(output, arg1, sizeof(BasicType) * allCalNum);

    QFile file(arg0);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
    {
        for (int i = 0;i < allCalNum;i++)
        {
            file.write(QString::number(arg1[i]).toStdString().c_str());
            file.write("\n");
        }
    }

    file.close();
}


LibFunction_t funcs[] = {
    LIB_FUNCTION(read_file, 2),
    LIB_FUNCTION(write_file, 2),
    LIB_FUNCTION(append_file, 2),
    END_OF_LIB
};

register_function_lib(funcs);
